import { useMount } from 'ahooks'
import { App, Skeleton } from "antd"
import { useRequest } from 'alova/client'
import { memo, useEffect, useState } from 'react'

import { API_Mapping, Http } from '../../Utils/Api'
import { FormTemplate } from '../../Utils/FormTemp'
import { FieldMapping } from '../../Config/Mapping'
import { fromStore } from '../../Config/zustand'

const FromFields = memo(({ data, Off }) => {
    const [columns, setColumns] = useState()
    const { fromData } = fromStore()
    const { init, fields, DevEvent } = data
    const { send } = useRequest(params => Http({ url, params }), { immediate: false })

    useEffect(() => {
        if (JSON.stringify(fromData) !== '{}') {
            DevEvent.emit({ type: 'fieldBack', data: fromData })
            Off()
        }
    }, [fromData])
    const setMapping = async (item) => {
        const { mappingType, mappingData } = item
        if (mappingType === 'DataMapping') return FieldMapping[mappingData]
        if (mappingType === 'ApiMapping') return await API_Mapping[mappingData]()
        return []
    }

    const getColumns = async () => await Promise.all(fields.map(async item => {
        const data = {
            title: item.caption,
            dataIndex: item.dataField,
            valueType: item.valueType || 'kong',
            rules: item.rules,
            isAdded: item.isAdded,
            isModify: item.isModify,
            format: item.format
        }
        if (item.valueType === 'Radio' ||
            item.valueType === 'Select' ||
            item.valueType === 'SelectMultiple' ||
            item.valueType === 'TreeSelect' ||
            item.valueType === 'TreeSelectMultiple'
        ) {
            data.valueEnum = await setMapping(item)
        }
        return data
    }))
    useMount(() => getColumns().then(res => setColumns(res)))

    return (
        <div>
            {columns ?
                <FormTemplate columns={columns} init={init} /> :
                <Skeleton active />
            }
        </div>
    );
})

export default FromFields;